<template>
  <AdminLayout>
    <div class="reviews-management" style="min-height: calc(100vh - 60px);">
      <div class="page-header">
        <h2>评论管理</h2>
      </div>
      
      <div class="search-filter">
        <div class="search-box">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M11 19C15.42 19 19 15.42 19 11C19 6.58 15.42 3 11 3C6.58 3 3 6.58 3 11C3 15.42 6.58 19 11 19ZM21 21L16.65 16.65" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <input type="text" placeholder="搜索评论内容或客户名..." v-model="searchQuery"/>
        </div>
        <div class="filter-select">
          <select v-model="productFilter">
            <option value="all">全部产品</option>
            <option v-for="product in products" :key="product.id" :value="product.id">
              {{ product.name }}
            </option>
          </select>
        </div>
        <div class="filter-select">
          <select v-model="ratingFilter">
            <option value="all">全部评分</option>
            <option value="5">5星</option>
            <option value="4">4星</option>
            <option value="3">3星</option>
            <option value="2">2星</option>
            <option value="1">1星</option>
          </select>
        </div>
        <div class="search-actions">
          <button class="add-button" @click="openAddReviewModal">
            新增评论
          </button>
          <button class="search-button" @click="performSearch">
            搜索
          </button>
          <button class="reset-button" @click="resetFilters">
            重置
          </button>
        </div>
      </div>
      
      <div class="reviews-table-container">
        <table class="reviews-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>产品</th>
              <th>客户</th>
              <th>评分</th>
              <th>评论内容</th>
              <th>评论时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="review in filteredReviews" :key="review.id">
              <td>{{ review.id }}</td>
              <td>{{ getProductName(review.productId) }}</td>
              <td>{{ review.customerName }}</td>
              <td>
                <div class="rating-stars">
                  <span v-for="i in 5" :key="i" class="star" :class="{ filled: i <= review.rating }">★</span>
                </div>
              </td>
              <td class="review-content">{{ review.content }}</td>
              <td>{{ formatDateTime(review.createdAt) }}</td>
              <td>
                <div class="action-buttons">
                  <button class="reply-button" @click="replyToReview(review.id)">
                    回复
                  </button>
                  <button class="delete-button" @click="deleteReview(review.id)">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div v-if="filteredReviews.length === 0" class="no-data">
          <p>暂无评论数据</p>
        </div>
      </div>
      
      <div class="pagination">
        <button class="pagination-button" :disabled="currentPage === 1" @click="currentPage--">
          上一页
        </button>
        <div class="page-numbers">
          <span v-for="page in totalPages" :key="page" 
                class="page-number" :class="{ active: page === currentPage }"
                @click="currentPage = page">
            {{ page }}
          </span>
        </div>
        <button class="pagination-button" :disabled="currentPage === totalPages" @click="currentPage++">
          下一页
        </button>
      </div>
      
      <!-- 回复评论弹窗 -->
      <div v-if="showReplyModal" class="modal-overlay" @click="closeReplyModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>回复评论</h3>
            <button class="close-button" @click="closeReplyModal">×</button>
          </div>
          <div class="modal-body">
            <div v-if="currentReview" class="review-info">
              <div class="review-product">产品：{{ getProductName(currentReview.productId) }}</div>
              <div class="review-customer">客户：{{ currentReview.customerName }}</div>
              <div class="review-rating">
                评分：
                <div class="rating-stars">
                  <span v-for="i in 5" :key="i" class="star" :class="{ filled: i <= currentReview.rating }">★</span>
                </div>
              </div>
              <div class="review-content">评论：{{ currentReview.content }}</div>
            </div>
            <form @submit.prevent="submitReply">
              <div class="form-group">
                <label>回复内容 *</label>
                <textarea v-model="replyContent" required placeholder="请输入回复内容..."></textarea>
              </div>
              <div class="form-actions">
                <button type="button" class="cancel-button" @click="closeReplyModal">取消</button>
                <button type="submit" class="save-button">提交回复</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 新增评论弹窗 -->
      <div v-if="showAddReviewModal" class="modal-overlay" @click="closeAddReviewModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>新增评论</h3>
            <button class="close-button" @click="closeAddReviewModal">×</button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="submitNewReview">
              <div class="form-group">
                <label>选择产品 *</label>
                <select v-model="newReview.productId" required class="form-input">
                  <option value="" disabled>请选择产品</option>
                  <option v-for="product in products" :key="product.id" :value="product.id">
                    {{ product.name }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label>客户姓名 *</label>
                <input type="text" v-model="newReview.customerName" required placeholder="请输入客户姓名" class="form-input"/>
              </div>

              <div class="form-group">
                <label>评分 *</label>
                <div class="rating-input">
                  <span v-for="i in 5" :key="i" class="star-rating" :class="{ filled: i <= newReview.rating }" @click="setRating(i)">
                    ★
                  </span>
                </div>
              </div>

              <div class="form-group">
                <label>评论内容 *</label>
                <textarea v-model="newReview.content" required placeholder="请输入评论内容..." class="form-input"></textarea>
              </div>

              <div class="form-group">
                <label>上传图片</label>
                <div class="image-upload">
                  <input type="file" ref="reviewImageInput" accept="image/*" style="display: none" @change="handleImageUpload"/>
                  <button type="button" class="upload-btn" @click="triggerImageUpload">
                    {{ newReview.imageUrl ? '更换图片' : '点击上传图片' }}
                  </button>
                  <div v-if="newReview.imageUrl" class="image-preview-small">
                    <img :src="newReview.imageUrl" alt="Review image"/>
                    <button type="button" class="remove-image-btn" @click="removeImage">移除</button>
                  </div>
                </div>
              </div>

              <div class="form-actions">
                <button type="button" class="cancel-button" @click="closeAddReviewModal">取消</button>
                <button type="submit" class="save-button">添加评论</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script>
import AdminLayout from './AdminLayout.vue'
import ReviewStore from '../../services/ReviewStore.js'
import ProductStore from '../../services/ProductStore.js'

export default {
  name: 'ReviewsManagement',
  components: {
    AdminLayout
  },
  data() {
    return {
      reviews: [],
      products: [],
      searchQuery: '',
      productFilter: 'all',
      ratingFilter: 'all',
      currentPage: 1,
      itemsPerPage: 10,
      showReplyModal: false,
      currentReview: null,
      replyContent: '',
      showAddReviewModal: false,
      newReview: {
        productId: '',
        customerName: '',
        customerId: Math.floor(Math.random() * 1000),
        rating: 5,
        content: '',
        imageUrl: '',
        createdAt: new Date().toISOString(),
        reply: null
      }
    }
  },
  created() {
    // 添加监听器，当ReviewStore数据更新时刷新页面
    ReviewStore.addListener(this.loadReviews);
    // 加载产品列表
    this.loadProducts();
    // 加载评论数据
    this.loadReviews();
  },
  beforeUnmount() {
    // 移除监听器
    ReviewStore.removeListener(this.loadReviews);
  },
  computed: {
    filteredReviews() {
      let result = [...this.reviews];
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(review => 
          review.content.toLowerCase().includes(query) ||
          review.customerName.toLowerCase().includes(query)
        );
      }
      
      // 产品过滤
      if (this.productFilter !== 'all') {
        result = result.filter(review => review.productId === parseInt(this.productFilter));
      }
      
      // 评分过滤
      if (this.ratingFilter !== 'all') {
        result = result.filter(review => review.rating === parseInt(this.ratingFilter));
      }
      
      // 按评论时间降序排序
      result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      
      // 分页
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      return result.slice(startIndex, endIndex);
    },
    totalPages() {
      let result = [...this.reviews];
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(review => 
          review.content.toLowerCase().includes(query) ||
          review.customerName.toLowerCase().includes(query)
        );
      }
      
      // 产品过滤
      if (this.productFilter !== 'all') {
        result = result.filter(review => review.productId === parseInt(this.productFilter));
      }
      
      // 评分过滤
      if (this.ratingFilter !== 'all') {
        result = result.filter(review => review.rating === parseInt(this.ratingFilter));
      }
      
      return Math.ceil(result.length / this.itemsPerPage);
    }
  },
  methods: {
    async loadReviews() {
      // 如果ReviewStore还没有加载过数据，则触发加载
      if (!ReviewStore.isLoading && this.reviews.length === 0) {
        await ReviewStore.loadReviews();
      }
      // 从ReviewStore获取所有评论
      this.reviews = ReviewStore.getAllReviews();
    },
    
    async loadProducts() {
      // 加载产品列表，用于显示评论关联的产品名称
      if (!ProductStore.isLoading && this.products.length === 0) {
        await ProductStore.loadProducts();
      }
      this.products = ProductStore.getAllProducts();
    },
    
    performSearch() {
      this.currentPage = 1;
    },
    
    resetFilters() {
      this.searchQuery = '';
      this.productFilter = 'all';
      this.ratingFilter = 'all';
      this.currentPage = 1;
    },

    // 打开新增评论弹窗
    openAddReviewModal() {
      this.newReview = {
        productId: '',
        customerName: '',
        customerId: Math.floor(Math.random() * 1000),
        rating: 5,
        content: '',
        imageUrl: '',
        createdAt: new Date().toISOString(),
        reply: null
      };
      this.showAddReviewModal = true;
    },

    // 关闭新增评论弹窗
    closeAddReviewModal() {
      this.showAddReviewModal = false;
    },

    // 触发图片上传
    triggerImageUpload() {
      this.$refs.reviewImageInput.click();
    },

    // 处理图片上传
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.newReview.imageUrl = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },

    // 移除图片
    removeImage() {
      this.newReview.imageUrl = '';
      this.$refs.reviewImageInput.value = '';
    },

    // 设置评分
    setRating(rating) {
      this.newReview.rating = rating;
    },

    // 提交新增评论
    async submitNewReview() {
      if (!this.newReview.productId || !this.newReview.customerName || !this.newReview.content) {
        alert('请填写必填字段');
        return;
      }

      // 添加评论到数据存储
      const success = await ReviewStore.addReview(this.newReview);
      if (success) {
        this.closeAddReviewModal();
        // 重新加载数据
        this.loadReviews();
        // 如果有产品过滤，确保新增的评论也能被正确过滤
        if (this.productFilter !== 'all') {
          this.currentPage = 1;
        }
      } else {
        alert('添加评论失败，请重试。');
      }
    },
    
    getProductName(productId) {
      const product = this.products.find(p => p.id === productId);
      return product ? product.name : '未知产品';
    },
    
    replyToReview(id) {
      const review = ReviewStore.getReviewById(id);
      if (review) {
        this.currentReview = { ...review };
        this.replyContent = '';
        this.showReplyModal = true;
      }
    },
    
    async deleteReview(id) {
      if (confirm('确定要删除此评论吗？此操作不可撤销。')) {
        const success = await ReviewStore.deleteReview(id);
        if (success) {
          // 如果删除的是当前页面的最后一条数据，且当前页不是第一页，则返回上一页
          if (this.filteredReviews.length === 1 && this.currentPage > 1) {
            this.currentPage--;
          }
        } else {
          alert('删除评论失败，请重试。');
        }
      }
    },
    
    async submitReply() {
      if (this.currentReview && this.replyContent.trim()) {
        // 创建回复数据
        const updatedReview = {
          ...this.currentReview,
          reply: {
            content: this.replyContent.trim(),
            createdAt: new Date().toISOString()
          }
        };
        
        const success = await ReviewStore.updateReview(this.currentReview.id, updatedReview);
        if (success) {
          this.closeReplyModal();
        } else {
          alert('回复评论失败，请重试。');
        }
      }
    },
    
    closeReplyModal() {
      this.showReplyModal = false;
      this.currentReview = null;
      this.replyContent = '';
    },
    
    formatDateTime(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
}
</script>

<style scoped>
.reviews-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.search-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.search-box {
  position: relative;
  flex: 1;
  min-width: 280px;
  max-width: 500px;
}

.search-box svg {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
}

.search-box input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.filter-select {
  min-width: 150px;
}

.filter-select select {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
}

.search-actions {
  display: flex;
  gap: 10px;
}

.search-button {
  padding: 12px 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-button:hover {
  background-color: #45a049;
}

.reset-button {
  padding: 12px 20px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reset-button:hover {
  background-color: #e0e0e0;
  border-color: #ccc;
}

.reviews-table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
  max-height: 620px;
  overflow-y: auto;
}

.reviews-table {
  width: 100%;
  border-collapse: collapse;
}

.reviews-table th,
.reviews-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.reviews-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #333;
  font-size: 14px;
  position: sticky;
  top: 0;
  z-index: 1;
}

.reviews-table td {
  font-size: 14px;
  color: #666;
}

.rating-stars {
  display: flex;
  gap: 2px;
}

.star {
  color: #ddd;
  font-size: 16px;
}

.star.filled {
  color: #ffc107;
}

.review-content {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.reply-button {
  padding: 6px 12px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reply-button:hover {
  background-color: #1976d2;
}

.delete-button {
  padding: 6px 12px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: #d32f2f;
}

.no-data {
  padding: 60px 20px;
  text-align: center;
  color: #999;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 20px;
  margin-left: 20px;
  padding: 10px 0;
}

.pagination-button {
  padding: 6px 12px;
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 60px;
  text-align: center;
}

.pagination-button:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.pagination-button:disabled {
  color: #d9d9d9;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-number {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-number:hover {
  background-color: #f5f5f5;
  border-color: #ccc;
}

.page-number.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-button:hover {
  background-color: #f5f5f5;
  color: #333;
}

/* Review info styles */
.review-info {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.review-product,
.review-customer,
.review-rating {
  margin-bottom: 10px;
  font-size: 14px;
}

.review-product {
  font-weight: 500;
  color: #333;
}

.review-customer {
  color: #666;
}

.review-content {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
  line-height: 1.6;
  color: #333;
}

/* Form styles */
.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-group textarea {
  width: 100%;
  min-height: 120px;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  resize: vertical;
  transition: border-color 0.3s ease;
}

.form-group textarea:focus {
  outline: none;
  border-color: #4caf50;
}

.form-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.cancel-button {
  padding: 10px 20px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-button:hover {
  background-color: #e0e0e0;
  border-color: #ccc;
}

.save-button {
  padding: 10px 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.save-button:hover {
  background-color: #45a049;
}

/* Rating input styles */
.rating-input {
  display: flex;
  gap: 4px;
}

.star-rating {
  font-size: 24px;
  color: #ddd;
  cursor: pointer;
  transition: color 0.2s ease;
}

.star-rating.filled {
  color: #ffc107;
}

.star-rating:hover {
  color: #ffc107;
}

/* Image upload styles */
.image-upload {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.upload-btn {
  padding: 10px 15px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px dashed #ddd;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: fit-content;
}

.upload-btn:hover {
  background-color: #e8f5e9;
  border-color: #4caf50;
  color: #4caf50;
}

.image-preview-small {
  position: relative;
  max-width: 200px;
  margin-top: 10px;
}

.image-preview-small img {
  width: 100%;
  height: auto;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.remove-image-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(244, 67, 54, 0.8);
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: background-color 0.3s ease;
}

.remove-image-btn:hover {
  background-color: #f44336;
}

/* Responsive design */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .reviews-table-container {
    overflow-x: auto;
  }
  
  .reviews-table {
    min-width: 800px;
  }
  
  .review-content {
    max-width: 200px;
  }
  
  .modal-content {
    margin: 20px;
    padding: 20px;
  }
}
</style>